//
//  LYHeaderImageEditorView.m
//  SZBank
//
//  Created by LuoYao on 16/7/21.
//  Copyright © 2016年 LuoYao. All rights reserved.
//  编辑图片页面

#import "LYHeaderImageEditorView.h"


@interface LYHeaderImageEditorView ()<UIScrollViewDelegate>
{
    UIImageView *alertImageView;
    UIImageView *imageView;/**< 传来的图片 */
    UIImage *headerImage;/**< 传来的图片 */
    UIImageView *headerImageView;/**< 圆圈 */
    
}
@property (nonatomic) UIScrollView *scrollView;/**< 滚动视图，用于装载 */
@end
@implementation LYHeaderImageEditorView


- (instancetype)initWithFrame:(CGRect)frame withImage:(UIImage *)image
{
    self = [super initWithFrame:frame];
    if (self) {
        
        headerImage = image;
        
        //背景
        self.backImageView.image = [LocalDataManager getImageWithSourceOfPath:@"个人信息_拍照_背景"];
        
        //提示框
        alertImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _cKwidth * 0.25, _cKheight * 0.07)];
        alertImageView.center = CGPointMake(_cKwidth * 0.5, _cKheight * 0.1);
        alertImageView.image = [LocalDataManager getImageWithSourceOfPath:@"个人信息_拍照_头像_03"];
        
        
        
        //传来的图片
        imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = self.bounds;
        
        imageView.center = self.backImageView.center;
        imageView.backgroundColor = [UIColor clearColor];
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [self.scrollView addSubview:imageView];
        [self addSubview:self.scrollView];
        
        
        
        NSArray *btns = @[@"个人信息_拍照_头像_07",@"个人信息_拍照_头像_09",@"个人信息_拍照_头像_11"];
        
        for (int i = 0; i < btns.count; i ++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(_cKwidth * 0.3 + i * _cKwidth * 0.15, _cKheight * 0.7, _cKwidth * 0.1, _cKheight * 0.05)];
            [btn setBackgroundImage:[LocalDataManager getImageWithSourceOfPath:btns[i]] forState:UIControlStateNormal];
            btn.tag = 1000 + i;
            [btn addTarget:self action:@selector(action_btnClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self addSubview:btn];
        }
        
        
        //圆圈
        headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _cKwidth * 0.3, _cKwidth * 0.3)];
        headerImageView.center = CGPointMake(self.center.x, _cKheight * 0.4);
        headerImageView.image = [LocalDataManager getImageWithSourceOfPath:@"个人信息_头像1"];
        headerImageView.backgroundColor = [UIColor clearColor];
        [self addSubview:headerImageView];
        
        
        [self addSubview:alertImageView];
        [self alertImageAnimation];
        
    }
    return self;
}


#pragma mark - 动画方法
- (void)alertImageAnimation{
    [UIView animateWithDuration:3 animations:^{
        
        [UIView setAnimationRepeatCount:INT_MAX];
        
        alertImageView.alpha = 0.1;
        
    } completion:^(BOOL finished) {
        alertImageView.alpha = 1;
    }];
}


//图片存本地、网络
- (void)saveImageWithImage:(UIImage *)image{
    //转换为data,并缩小
        NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    
    //存网络
        NSString *base64String = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        NSDictionary *dic = @{@"managerId":[PersonInfoSingle defaultPersonInfo].loginPersonInfo[@"ID"],@"returnData":base64String,@"imageType":@"jpg"};
    
        [NetWorkingDataManager getProtocolCustomerUploadFileSaveWithParam:dic success:^(id sender) {
            NSLog(@"ok%@",sender);
        } failure:nil];
    
    
    //存本地
        [LocalDataManager saveImageWithData:imageData];
}


//点击事件方法
- (void)action_btnClick:(UIButton *)sender{
    switch (sender.tag - 1000) {
        case 0:
        {
             UIImage *editorImage = [self creatSnapshot];
            
            [self saveImageWithImage:editorImage];
        }
            break;
            
        case 1:
        {//返回重新选择
            
        }
            break;
            
        default:
            break;
    }
    
    [self removeFromSuperview];
}

#pragma mark - 头像剪裁

- (UIImage *)creatSnapshot {
    
    //获取在scrollView上的位置
    UIGraphicsBeginImageContextWithOptions(self.scrollView.bounds.size, YES, 0);
    [self.scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapshot_1 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //得到位置
    CGRect locationRect = [self convertRect:headerImageView.frame toView:self.scrollView];
    //调用方法截取图片
    UIImage *userImage = [self createSubImageForImage:snapshot_1 withRect:locationRect];
    headerImageView.image = userImage;
    
    //新建一个view用来拼接
    UIImageView *imageVe = [[UIImageView alloc] initWithFrame:headerImageView.bounds];
    imageVe.image = [LocalDataManager getImageWithSourceOfPath:@"个人信息_头像2"];
    [headerImageView addSubview:imageVe];
    
    //合成为一个图
    UIGraphicsBeginImageContextWithOptions(headerImageView.bounds.size, YES, 0);
    [headerImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *snapshot_2 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [imageVe removeFromSuperview];
    
    return snapshot_2;
}


- (UIImage *)createSubImageForImage:(UIImage *)image withRect:(CGRect)rect {
    // 方法1
    CGRect drawRect = CGRectMake(rect.origin.x * image.scale,
                                 rect.origin.y * image.scale,
                                 rect.size.width * image.scale,
                                 rect.size.height * image.scale);
    
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, drawRect);
    CGRect subImageBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(subImageBounds.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextDrawImage(ctx, subImageBounds, subImageRef);
    
    UIImage *subImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    
    CGImageRelease(subImageRef);
    
    return subImage;
    
}


#pragma mark - UIScrollViewDelegate 
//取消快速滑动后的减速惯性
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (decelerate)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [scrollView setContentOffset:scrollView.contentOffset animated:NO];
        });
    }
}


//缩放结束之后
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    //将当前缩放系数作为图片尺寸
    [self.scrollView setZoomScale:scale animated:NO];
}
//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return imageView;
}
#pragma mark - getter
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.backImageView.bounds];
        _scrollView.center = self.backImageView.center;
        _scrollView.contentSize = CGSizeMake(_cKwidth * 2, _cKheight * 2);
        _scrollView.backgroundColor = [UIColor clearColor];
        
        _scrollView.delegate = self;
        
        
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.bounces = NO;
        
        //放大倍数
        _scrollView.maximumZoomScale = 2.f;
        //缩小倍数
        _scrollView.minimumZoomScale = 0.5f;
        
        _scrollView.delegate = self;
    }
    return _scrollView;
}






@end
